package logic

import (
	"context"
	"strconv"
	"three-sxp/models/es"
	"three-sxp/models/mysql"

	"three-sxp/goodsrpc/goodsrpc"
	"three-sxp/goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateGoodsLogic {
	return &CreateGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// CreateGoods todo: 商品添加
func (l *CreateGoodsLogic) CreateGoods(in *goodsrpc.CreateGoodsRequest) (*goodsrpc.CreateGoodsResponse, error) {
	// todo: add your logic here and delete this line
	goods, _ := mysql.GetGoodsInfo(mysql.Goods{
		GoodsName: in.GoodsName,
	})
	if goods.ID != 0 {
		goods.GoodsStock += int(in.GoodsStock)
		_, err := mysql.SaveGoods(goods)
		if err != nil {
			return &goodsrpc.CreateGoodsResponse{
				Code: 400,
				Msg:  "修改库存失败",
			}, nil
		}
		for i := 1; i <= int(in.GoodsStock); i++ {
			mysql.Redis.LPush(context.Background(), "goods:"+strconv.Itoa(int(goods.ID)), goods.GoodsName)
		}
		return &goodsrpc.CreateGoodsResponse{
			Code: 200,
			Msg:  "商品添加成功",
		}, nil
	}
	//todo： mysql
	res, err := mysql.CreateGoods(mysql.Goods{
		GoodsName:    in.GoodsName,
		GoodsPrice:   float64(in.GoodsPrice),
		GoodsStock:   int(in.GoodsStock),
		GoodsDetails: in.GoodsDetails,
	})
	if err != nil {
		return &goodsrpc.CreateGoodsResponse{
			Code: 400,
			Msg:  "商品发布失败",
		}, nil
	}
	//todo：redis
	for i := 1; i <= int(in.GoodsStock); i++ {
		mysql.Redis.LPush(context.Background(), "goods:"+strconv.Itoa(int(res.ID)), res.GoodsName)
	}
	//todo：es
	err = es.AddEs("goods", res)
	if err != nil {
		return &goodsrpc.CreateGoodsResponse{
			Code: 400,
			Msg:  "es同步失败",
		}, nil
	}
	return &goodsrpc.CreateGoodsResponse{
		Code: 200,
		Msg:  "商品发布成功",
	}, nil
}
